package base.util;

import org.apache.commons.lang3.RandomUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : GuoFei
 * @date : 2018/12/30 13:55
 */
public class ThreadPoolUtil {
//    static volatile AtomicInteger count = new AtomicInteger(0);

    static int countInt = 0;

    public static void main(String[] args) {
        System.out.println("begin");
        ExecutorService threadPool = getThreadPool();
        for (int i = 0; i < 1000; i++) {
            int finalNum = i;
            threadPool.submit(() -> runNum(finalNum));
        }
        System.out.println("end");
    }

    private static ExecutorService getThreadPool() {

        ExecutorService threadPool;
        // 0,max,SynchronousQueue
        threadPool = Executors.newCachedThreadPool();
//        threadPool.shutdown();
        // n,n,LinkedBlockingQueue
//        threadPool = Executors.newFixedThreadPool(10);
        // 1,max,DelayedWorkQueue
//        threadPool = Executors.newSingleThreadScheduledExecutor();
        // n,max,DelayedWorkQueue
//        threadPool = Executors.newScheduledThreadPool(10);

//        threadPool = new ThreadPoolExecutor(1,1,0L,TimeUnit.MILLISECONDS, new SynchronousQueue<>());
        return threadPool;
    }

    private static void runNum(int num) {
        try {
            Thread.sleep(RandomUtils.nextLong(1000, 5000));
//            count.getAndIncrement();
            countIncrement();
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.err.println(num + "---有誤");
        }
        System.out.println(Thread.currentThread().getName() + "---" + num + "---" + countInt);
    }

    synchronized private static void countIncrement(){
        countInt++;
    }



}







